import { defineStore } from 'pinia'

export const useToastStore = defineStore('toast', {
  state: () => ({
    toasts: [] // { id, title, message, type, dismissible, duration }
  }),
  actions: {
    show(options) {
      const id = Date.now() + Math.random()
      const toast = {
        id,
        title: options.title || '',
        message: options.message || options.text || '',
        type: options.type || 'info',
        dismissible: options.dismissible !== false,
        duration: options.duration || 3000
      }
      
      this.toasts.push(toast)
      
      if (toast.duration > 0) {
        setTimeout(() => {
          this.removeToast(id)
        }, toast.duration)
      }
      
      return id
    },
    
    success(message, options = {}) {
      return this.show({
        ...options,
        message,
        type: 'success',
        duration: options.duration || 3000
      })
    },
    
    error(message, options = {}) {
      return this.show({
        ...options,
        message,
        type: 'error',
        duration: options.duration || 4000
      })
    },
    
    warning(message, options = {}) {
      return this.show({
        ...options,
        message,
        type: 'warning',
        duration: options.duration || 3500
      })
    },
    
    info(message, options = {}) {
      return this.show({
        ...options,
        message,
        type: 'info',
        duration: options.duration || 3000
      })
    },
    
    // 购买流程专用的通知方法
    purchaseSuccess(eventTitle, orderNo) {
      return this.success(`购买成功！`, {
        title: '订单已创建',
        message: `您已成功购买《${eventTitle}》的门票，订单号：${orderNo}`,
        duration: 5000
      })
    },
    
    addToCartSuccess(eventTitle, quantity) {
      return this.success(`已添加到购物车`, {
        title: '商品已添加',
        message: `《${eventTitle}》× ${quantity} 已添加到购物车`,
        duration: 3000
      })
    },
    
    loginRequired() {
      return this.warning('请先登录', {
        title: '需要登录',
        message: '购买门票需要先登录您的账户',
        duration: 4000
      })
    },
    
    removeToast(id) {
      this.toasts = this.toasts.filter(toast => toast.id !== id)
    },
    
    clear() {
      this.toasts = []
    },
    
    // 兼容旧的API
    remove(id) {
      this.removeToast(id)
    }
  },
  
  getters: {
    // 兼容旧的API
    messages: (state) => state.toasts.map(toast => ({
      id: toast.id,
      text: toast.message,
      type: toast.type
    }))
  }
})